<script setup lang="ts">
import { deleteAddressAPI } from '@/api/adress'
import { deleteProductsInCartAPI } from '@/api/cart'
import { postOrderAPI, getOrderListAPI } from '@/api/order'
import { useAddressStore } from '@/stores/address'
import { useCartStore } from '@/stores/cart'
import { useCouponStore } from '@/stores/coupon'
import { Message } from '@arco-design/web-vue'
import { storeToRefs } from 'pinia'
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'

const { selectedCartList, cartList } = storeToRefs(useCartStore())
const { getCartList } = useCartStore()
const { addressList, isAdressModalShow, defaultAddress, addressForm, statusName } = storeToRefs(useAddressStore())
const { setDefaultAddress, getAddressList } = useAddressStore()

const numTotal = computed(() => selectedCartList.value.reduce((pre: any, cur: any) => pre + cur.goodsNum, 0))
const priceTotal = computed(() =>
  selectedCartList.value.reduce((pre: any, cur: any) => pre + cur.goodsNum * cur.price, 0)
)

console.log('default', defaultAddress.value)
const discount = computed(() => +selectedCoupon.value.discount || 0)

const router = useRouter()

// 提交订单
const handleSubmitOrder = async () => {
  // if (addressList.value.length === 0) {
  //   Message.error('您还没有收货地址！')
  //   return
  // }

  const res: any = await postOrderAPI({
    products: selectedCartList.value,
    discount: discount.value,
    username: defaultAddress.value.username,
    phone: defaultAddress.value.phone,
    total: priceTotal.value - discount.value,
    address:
      defaultAddress.value.province +
      defaultAddress.value.city +
      defaultAddress.value.district +
      defaultAddress.value.address
  })
  console.log('///', res)

  const delProductsIds: number[] = selectedCartList.value.map((item: any) => item.id)
  cartList.value = cartList.value.filter((item: any) => !delProductsIds.includes(item.id))

  await deleteProductsInCartAPI({ products: cartList.value })
  await getCartList()
  router.push({
    path: '/payment',
    query: { total: res.total, id: res.id, address: res.address, username: res.username, phone: res.phone }
  })
}

const baseURL = import.meta.env.VITE_BASE_URL

const handleSetDefaultAddress = async (id: number) => {
  await setDefaultAddress(String(id))
  Message.success('更改默认地址成功！')
}

const handleDeleteAddress = async (id: number) => {
  await deleteAddressAPI(id)
  getAddressList()
  Message.success('删除成功！')
}

// 修改
const handleUpdateAddress = async (id: number) => {
  isAdressModalShow.value = true
  addressForm.value = { ...addressList.value.find((item: any) => item.id == id) }
  addressForm.value.area = [addressForm.value.province, addressForm.value.city, addressForm.value.district]
  statusName.value = '修改'
}

// 优惠券列表
const { couponList, selectedCoupon } = storeToRefs(useCouponStore())
const popoverShow = ref(false)
const handleSelectCoupon = (coupon: any) => {
  selectedCoupon.value = coupon
  popoverShow.value = false
}
</script>

<template>
  <div class="w-1280px mx-auto">
    <StepsBar title="确认订单" :current="1" />

    <div class="p-4 px-8 bg-#f9f9f9 mt-4 text-4">
      <div class="flex justify-between">
        <h2>收货地址</h2>
        <span @click="isAdressModalShow = true" class="cursor-pointer text-gray-4 decoration-underline">新增地址</span>
      </div>
      <div class="mt-6 w-80%">
        <div v-if="addressList.length" class="flex flex-col gap-3">
          <div
            v-for="(item, index) in addressList"
            :key="item.id"
            class="p-4 border border-gray-3 border-solid bg-white flex items-center justify-between"
          >
            <div class="flex items-center gap-2">
              <div class="w-30px">
                <icon-star-fill v-show="defaultAddress.id == item.id" class="text-2xl text-warning" />
              </div>
              <div>
                <div class="flex gap-4 items-center text-lg">
                  <span>{{ item.username }}</span>
                  <span>{{ item.phone }}</span>
                </div>

                <div class="flex gap-4 items-center text-4 mt-4 text-gray-5">
                  <span>{{ item.province }} {{ item.city }} {{ item.district }}</span>
                  <span>{{ item.address }}</span>
                </div>
              </div>
            </div>

            <div class="flex gap-4">
              <span
                v-show="defaultAddress.id != item.id"
                @click="handleSetDefaultAddress(item.id)"
                class="text-primary cursor-pointer"
                >设为默认</span
              >
              <span @click="handleUpdateAddress(item.id)" class="text-warning cursor-pointer">修改</span>
              <span @click="handleDeleteAddress(item.id)" class="text-error cursor-pointer">删除</span>
            </div>
          </div>
        </div>

        <div
          v-else
          class="p-4 border py-12 border-gray-3 border-solid text-center bg-white cursor-pointer flex items-center gap-4 justify-center"
        >
          <icon-plus class="text-gray-7" size="20" />
          <span @click="isAdressModalShow = true" class="text-gray-7 text-lg">请填写收货地址</span>
        </div>
      </div>
    </div>

    <div class="p-4 px-8 bg-#f9f9f9 mt-4 text-4">
      <h2>商品</h2>
      <div class="mt-4 p-4 bg-white flex flex-col">
        <div
          v-for="(item, index) in selectedCartList"
          :key="item.id"
          class="grid border-b-solid py-2 border-b border-b-gray-3"
          style="grid-template-columns: 3fr 1fr 1fr"
        >
          <div class="flex gap-4">
            <img class="w-80px h-80px" :src="baseURL + item.cover" alt="" />
            <div class="flex flex-col gap-2">
              <span>{{ item.name }}</span>
              <span class="text-gray">单位：{{ item.model }}</span>
            </div>
          </div>
          <div>
            <span>{{ item.price }}元 x {{ item.goodsNum }}</span>
          </div>
          <div>{{ item.price * item.goodsNum }}元</div>
        </div>
      </div>
    </div>

    <div class="p-4 px-8 bg-#f9f9f9 mt-4 text-4 flex items-center">
      <h2 class="w-70">配送方式</h2>
      <span class="color-red text-5">包邮</span>
    </div>

    <div class="p-4 px-8 bg-#f9f9f9 mt-4 text-4 flex justify-between">
      <div class="text-4 flex flex-1">
        <h2 class="w-70">使用优惠券</h2>
        <div class="color-gray-6 text-5">
          <a-popover v-model:popup-visible="popoverShow" position="bl" trigger="click">
            <div class="flex flex gap-2 cursor-pointer">
              <icon-plus-circle-fill />
              <span v-if="!selectedCoupon.name">使用优惠券</span>
              <div v-else class="flex flex-col gap-2">
                <span>已使用：{{ selectedCoupon.name }} ({{ selectedCoupon.discount }}元)</span>
              </div>
            </div>

            <template #content>
              <div class="w-400px">
                <p class="text-lg text-center text-red">选择优惠券</p>
                <div
                  v-if="couponList.length"
                  class="m-6 p-2 h-200px overflow-auto flex flex-col gap-4 coupon-container"
                >
                  <div
                    v-for="coupon in couponList"
                    @click="handleSelectCoupon(coupon)"
                    class="cursor-pointer p-2 border border-solid border-gray-3 rounded-lg flex justify-between"
                  >
                    <div>
                      <p class="text-lg text-black">{{ coupon.name }}</p>
                      <p class="text-gray-6">
                        {{ new Date(+coupon.deadline).toLocaleDateString().replace(/\//g, '-') }}
                      </p>
                    </div>
                    <div>
                      <p class="text-lg text-#CA141D">¥ {{ coupon.discount }}</p>
                      <p class="text-#CA141D">满0元可用</p>
                    </div>
                  </div>
                </div>
                <a-empty v-else />
              </div>
            </template>
          </a-popover>
          <p v-if="selectedCoupon.name" @click="selectedCoupon = {}" class="mt-3 text-warning text-4 cursor-pointer">
            取消使用
          </p>
        </div>
      </div>
      <div class="w-full flex flex-col items-end p-4 flex-1 text-gray-6 gap-2">
        <p class="text-4 flex gap-3 items-end w-300px">
          <span class="flex-1 text-right w-120px">商品件数:</span>
          <span class="text-#CA141D text-lg flex-1 text-right">{{ numTotal }}件 </span>
        </p>
        <p class="text-4 flex gap-3 items-end w-300px">
          <span class="flex-1 text-right w-120px">商品总价:</span>
          <span class="text-#CA141D text-lg flex-1 text-right">{{ priceTotal }}元</span>
        </p>
        <p class="text-4 flex gap-3 items-end w-300px">
          <span class="flex-1 text-right w-120px">优惠券抵扣:</span>
          <span class="text-#CA141D text-lg flex-1 text-right">- {{ discount }}元</span>
        </p>
        <p class="text-4 flex gap-3 items-end w-300px">
          <span class="flex-1 text-right w-120px">运费:</span>
          <span class="text-#CA141D text-lg flex-1 text-right">{{ 0 }}元</span>
        </p>
        <p class="text-4 flex gap-3 items-end w-300px">
          <span class="flex-1 text-right w-120px">应付金额:</span>
          <span class="text-#CA141D text-2xl flex-1 font-600 align-baseline text-right"
            >{{ priceTotal - discount }}元</span
          >
        </p>
        <a-button @click="handleSubmitOrder" class="bg-#ca141d! color-white! w-200px h-60px mt-10 text-xl!"
          >提交订单</a-button
        >
      </div>
    </div>
  </div>
  <AddressDialog />
</template>

<style scoped>
.coupon-container::-webkit-scrollbar {
  width: 0.5rem;
  border-radius: 8px;
  background: #dddee0;
}

.coupon-container::-webkit-scrollbar-thumb {
  border-radius: 8px;
  background: #dddee0;
}

.coupon-container::-webkit-scrollbar-track {
  border-radius: 8px;
  background: #eeeeee;
}
</style>
